package com.ruoyi.web.dingding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * 获取access_token工具类
 */
public class AccessTokenUtil {
    private static final Logger bizLogger = LoggerFactory.getLogger(AccessTokenUtil.class);

    private final static Map<String, Long> tokenMap = new HashMap();
    private static final String URL_GET_TOKKEN = "https://oapi.dingtalk.com/gettoken";

    public static String getToken() throws RuntimeException {
        try {
            if (expired(tokenMap)) {
                DefaultDingTalkClient client = new DefaultDingTalkClient(URL_GET_TOKKEN);
                OapiGettokenRequest request = new OapiGettokenRequest();

                request.setAppkey(Constant.INNER_APPKEY);
                request.setAppsecret(Constant.INNER_APPSECRET);
                request.setHttpMethod("GET");
                OapiGettokenResponse response = client.execute(request);
                String accessToken = response.getAccessToken();
                tokenMap.put(accessToken, System.currentTimeMillis());
                return accessToken;
            } else {
                String token = tokenMap.entrySet().iterator().next().getKey();
                return token;
            }

        } catch (ApiException e) {
            bizLogger.error("getAccessToken failed", e);
            throw new RuntimeException();
        }

    }

    private static boolean expired(Map<String, Long> tokenMap) {
        if (tokenMap.isEmpty()) {
            return true;
        }
        String token = tokenMap.entrySet().iterator().next().getKey();
        Long createTime = tokenMap.get(token);
        if ((System.currentTimeMillis() - createTime) / 1000 > 3600) {
            return true;
        }
        return false;
    }
}
